<template>
  <div class="data-dictionary">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="字典名称">
          <el-input v-model="searchForm.dictName" placeholder="请输入字典名称" clearable />
        </el-form-item>
        <el-form-item label="字典编码">
          <el-input v-model="searchForm.dictCode" placeholder="请输入字典编码" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="searchDictionaries">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card class="operation-card">
      <el-button type="primary" :icon="Plus" @click="openAddDialog">新增字典</el-button>
      <el-button type="danger" :icon="Delete" @click="batchDelete" :disabled="selectedDictionaries.length === 0">
        批量删除
      </el-button>
    </el-card>

    <!-- 字典列表 -->
    <el-card>
      <el-table
        :data="dictionaryList"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="字典ID" width="80" />
        <el-table-column prop="dictName" label="字典名称" />
        <el-table-column prop="dictCode" label="字典编码" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="dictType" label="字典类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.dictType === 1 ? 'success' : 'info'">
              {{ row.dictType === 1 ? '系统' : '业务' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" :icon="Edit" size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button type="info" :icon="List" size="small" @click="openDictDataDialog(row)">字典项</el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="deleteDictionary(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增字典' : '编辑字典'"
      width="500px"
      @close="closeDialog"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="form.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典编码" prop="dictCode">
          <el-input v-model="form.dictCode" placeholder="请输入字典编码" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-radio-group v-model="form.dictType">
            <el-radio :value="1">系统</el-radio>
            <el-radio :value="2">业务</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入字典描述" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveDictionary" :loading="saveLoading">
          {{ dialogType === 'add' ? '新增' : '更新' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 字典项管理对话框 -->
    <el-dialog
      v-model="dictDataDialogVisible"
      :title="`字典项管理 - ${currentDict.dictName}`"
      width="800px"
      @close="closeDictDataDialog"
    >
      <div class="dict-data-container">
        <!-- 字典项操作栏 -->
        <div class="dict-data-operation">
          <el-button type="primary" :icon="Plus" size="small" @click="openAddDictDataDialog">新增字典项</el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="batchDeleteDictData" :disabled="selectedDictData.length === 0">
            批量删除
          </el-button>
        </div>

        <!-- 字典项列表 -->
        <el-table
          :data="dictDataList"
          style="width: 100%"
          v-loading="dictDataLoading"
          @selection-change="handleDictDataSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="字典项ID" width="80" />
          <el-table-column prop="dictLabel" label="字典项名称" />
          <el-table-column prop="dictValue" label="字典项值" />
          <el-table-column prop="sort" label="排序" width="80" />
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-switch
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleDictDataStatusChange(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" :icon="Edit" size="small" @click="openEditDictDataDialog(row)">编辑</el-button>
              <el-button type="danger" :icon="Delete" size="small" @click="deleteDictData(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 字典项分页 -->
        <el-pagination
          v-model:current-page="dictDataCurrentPage"
          v-model:page-size="dictDataPageSize"
          :page-sizes="[10, 20, 50]"
          :total="dictDataTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleDictDataSizeChange"
          @current-change="handleDictDataCurrentChange"
          style="margin-top: 15px; text-align: right"
        />
      </div>
    </el-dialog>

    <!-- 字典项新增/编辑对话框 -->
    <el-dialog
      v-model="dictDataFormDialogVisible"
      :title="dictDataDialogType === 'add' ? '新增字典项' : '编辑字典项'"
      width="500px"
      @close="closeDictDataFormDialog"
    >
      <el-form ref="dictDataFormRef" :model="dictDataForm" :rules="dictDataRules" label-width="100px">
        <el-form-item label="字典项名称" prop="dictLabel">
          <el-input v-model="dictDataForm.dictLabel" placeholder="请输入字典项名称" />
        </el-form-item>
        <el-form-item label="字典项值" prop="dictValue">
          <el-input v-model="dictDataForm.dictValue" placeholder="请输入字典项值" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="dictDataForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="dictDataForm.remark" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dictDataForm.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDictDataFormDialog">取消</el-button>
        <el-button type="primary" @click="saveDictData" :loading="dictDataSaveLoading">
          {{ dictDataDialogType === 'add' ? '新增' : '更新' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, Refresh, List } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = ref({
  dictName: '',
  dictCode: '',
  status: ''
})

// 字典列表数据
const dictionaryList = ref([])
const loading = ref(false)
const selectedDictionaries = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框参数
const dialogVisible = ref(false)
const dialogType = ref('add')
const saveLoading = ref(false)

// 表单数据
const form = ref({
  id: '',
  dictName: '',
  dictCode: '',
  dictType: 1,
  description: '',
  sort: 0,
  status: 1
})

// 表单验证规则
const rules = {
  dictName: [
    { required: true, message: '请输入字典名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  dictCode: [
    { required: true, message: '请输入字典编码', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z_]+$/, message: '只能包含字母和下划线', trigger: 'blur' }
  ],
  dictType: [{ required: true, message: '请选择字典类型', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
}

const formRef = ref()

// 字典项管理相关
const dictDataDialogVisible = ref(false)
const currentDict = ref({})
const dictDataList = ref([])
const dictDataLoading = ref(false)
const selectedDictData = ref([])
const dictDataCurrentPage = ref(1)
const dictDataPageSize = ref(10)
const dictDataTotal = ref(0)

// 字典项表单
const dictDataFormDialogVisible = ref(false)
const dictDataDialogType = ref('add')
const dictDataSaveLoading = ref(false)
const dictDataForm = ref({
  id: '',
  dictId: '',
  dictLabel: '',
  dictValue: '',
  sort: 0,
  remark: '',
  status: 1
})

const dictDataFormRef = ref()

// 字典项表单验证规则
const dictDataRules = {
  dictLabel: [
    { required: true, message: '请输入字典项名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  dictValue: [
    { required: true, message: '请输入字典项值', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
}

// 模拟数据 - 实际项目中应该从API获取
const mockDictionaryData = [
  {
    id: 1,
    dictName: '用户状态',
    dictCode: 'user_status',
    dictType: 1,
    description: '用户账号状态字典',
    sort: 1,
    status: 1,
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    dictName: '课程状态',
    dictCode: 'course_status',
    dictType: 2,
    description: '课程状态字典',
    sort: 2,
    status: 1,
    createTime: '2024-01-15 11:00:00'
  },
  {
    id: 3,
    dictName: '性别',
    dictCode: 'gender',
    dictType: 1,
    description: '性别字典',
    sort: 3,
    status: 1,
    createTime: '2024-01-15 11:30:00'
  }
]

const mockDictData = {
  1: [
    { id: 1, dictId: 1, dictLabel: '启用', dictValue: '1', sort: 1, status: 1 },
    { id: 2, dictId: 1, dictLabel: '禁用', dictValue: '0', sort: 2, status: 1 }
  ],
  2: [
    { id: 3, dictId: 2, dictLabel: '草稿', dictValue: 'DRAFT', sort: 1, status: 1 },
    { id: 4, dictId: 2, dictLabel: '已发布', dictValue: 'PUBLISHED', sort: 2, status: 1 },
    { id: 5, dictId: 2, dictLabel: '已下架', dictValue: 'OFFLINE', sort: 3, status: 1 }
  ],
  3: [
    { id: 6, dictId: 3, dictLabel: '男', dictValue: 'MALE', sort: 1, status: 1 },
    { id: 7, dictId: 3, dictLabel: '女', dictValue: 'FEMALE', sort: 2, status: 1 },
    { id: 8, dictId: 3, dictLabel: '未知', dictValue: 'UNKNOWN', sort: 3, status: 1 }
  ]
}

// 加载字典列表
const loadDictionaryList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const filteredData = mockDictionaryData.filter(item => {
      const matchName = !searchForm.value.dictName || item.dictName.includes(searchForm.value.dictName)
      const matchCode = !searchForm.value.dictCode || item.dictCode.includes(searchForm.value.dictCode)
      const matchStatus = searchForm.value.status === '' || item.status === searchForm.value.status
      return matchName && matchCode && matchStatus
    })
    
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    dictionaryList.value = filteredData.slice(start, end)
    total.value = filteredData.length
  } catch (error) {
    ElMessage.error('获取字典列表失败')
    console.error('Failed to load dictionary list:', error)
  } finally {
    loading.value = false
  }
}

// 搜索字典
const searchDictionaries = () => {
  currentPage.value = 1
  loadDictionaryList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    dictName: '',
    dictCode: '',
    status: ''
  }
  currentPage.value = 1
  loadDictionaryList()
}

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedDictionaries.value = val
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  loadDictionaryList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadDictionaryList()
}

// 处理状态变化
const handleStatusChange = async (row) => {
  try {
    // 模拟API调用
    ElMessage.success('状态更新成功')
  } catch (error) {
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

// 打开新增对话框
const openAddDialog = () => {
  dialogType.value = 'add'
  form.value = {
    id: '',
    dictName: '',
    dictCode: '',
    dictType: 1,
    description: '',
    sort: 0,
    status: 1
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (row) => {
  form.value = { ...row }
  dialogType.value = 'edit'
  dialogVisible.value = true
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 保存字典
const saveDictionary = async () => {
  try {
    await formRef.value.validate()
    saveLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success(dialogType.value === 'add' ? '新增字典成功' : '更新字典成功')
    closeDialog()
    loadDictionaryList()
  } catch (error) {
    if (error !== false) {
      ElMessage.error(dialogType.value === 'add' ? '新增字典失败' : '更新字典失败')
    }
  } finally {
    saveLoading.value = false
  }
}

// 删除字典
const deleteDictionary = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该字典吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('删除字典成功')
    loadDictionaryList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除字典失败')
    }
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedDictionaries.value.length === 0) {
    ElMessage.warning('请选择要删除的字典')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedDictionaries.value.length} 个字典吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('批量删除字典成功')
    loadDictionaryList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除字典失败')
    }
  }
}

// 打开字典项管理对话框
const openDictDataDialog = (row) => {
  currentDict.value = row
  dictDataDialogVisible.value = true
  loadDictDataList()
}

// 加载字典项列表
const loadDictDataList = async () => {
  dictDataLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    
    const data = mockDictData[currentDict.value.id] || []
    const start = (dictDataCurrentPage.value - 1) * dictDataPageSize.value
    const end = start + dictDataPageSize.value
    dictDataList.value = data.slice(start, end)
    dictDataTotal.value = data.length
  } catch (error) {
    ElMessage.error('获取字典项列表失败')
    console.error('Failed to load dict data list:', error)
  } finally {
    dictDataLoading.value = false
  }
}

// 关闭字典项管理对话框
const closeDictDataDialog = () => {
  dictDataDialogVisible.value = false
  currentDict.value = {}
  dictDataList.value = []
}

// 字典项相关方法
const handleDictDataSelectionChange = (val) => {
  selectedDictData.value = val
}

const handleDictDataSizeChange = (val) => {
  dictDataPageSize.value = val
  loadDictDataList()
}

const handleDictDataCurrentChange = (val) => {
  dictDataCurrentPage.value = val
  loadDictDataList()
}

const handleDictDataStatusChange = async (row) => {
  try {
    ElMessage.success('状态更新成功')
  } catch (error) {
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

const openAddDictDataDialog = () => {
  dictDataDialogType.value = 'add'
  dictDataForm.value = {
    id: '',
    dictId: currentDict.value.id,
    dictLabel: '',
    dictValue: '',
    sort: 0,
    remark: '',
    status: 1
  }
  dictDataFormDialogVisible.value = true
}

const openEditDictDataDialog = (row) => {
  dictDataForm.value = { ...row }
  dictDataDialogType.value = 'edit'
  dictDataFormDialogVisible.value = true
}

const closeDictDataFormDialog = () => {
  dictDataFormDialogVisible.value = false
  dictDataFormRef.value?.resetFields()
}

const saveDictData = async () => {
  try {
    await dictDataFormRef.value.validate()
    dictDataSaveLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success(dictDataDialogType.value === 'add' ? '新增字典项成功' : '更新字典项成功')
    closeDictDataFormDialog()
    loadDictDataList()
  } catch (error) {
    if (error !== false) {
      ElMessage.error(dictDataDialogType.value === 'add' ? '新增字典项失败' : '更新字典项失败')
    }
  } finally {
    dictDataSaveLoading.value = false
  }
}

const deleteDictData = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该字典项吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('删除字典项成功')
    loadDictDataList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除字典项失败')
    }
  }
}

const batchDeleteDictData = async () => {
  if (selectedDictData.value.length === 0) {
    ElMessage.warning('请选择要删除的字典项')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedDictData.value.length} 个字典项吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('批量删除字典项成功')
    loadDictDataList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除字典项失败')
    }
  }
}

// 初始化加载
onMounted(() => {
  loadDictionaryList()
})
</script>

<style scoped>
.data-dictionary {
  padding: 20px;
}

.search-card,
.operation-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.dict-data-container {
  padding: 10px;
}

.dict-data-operation {
  margin-bottom: 15px;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    width: 100%;
  }
}
</style>